<?php


namespace app\admin\controller\jizhan;

use app\admin\model\HtnsActivity;
use app\admin\model\HtnsActivityProduct;
use app\admin\model\HtnsActivityProductCate;
use app\admin\model\HtnsBasestationStore;
use app\admin\model\HtnsFdOrder;
use app\admin\model\HtnsOrder;
use app\admin\model\HtnsProduct;
use app\admin\traits\Curd;
use app\api\services\ActivityProductService;
use app\common\controller\AdminController;
use app\model\product\product\StoreProduct;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use jianyan\excel\Excel;
use think\App;
use think\Exception;

/**
 * Class Admin
 * @package app\admin\controller\system
 * @ControllerAnnotation(title="基站-品牌联盟-订单返点记录")
 */
class ReturnPointOrder extends AdminController
{

    use Curd;
    protected $storeId ; // 门店id

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new HtnsFdOrder();

        $user = session('admin');
        // 查询用户角色及权限
        $where['phone'] = $user['username'];
        $userInfo = \app\admin\model\HtnsUser::where($where)->find();
        if($userInfo){
            if($userInfo['jmyc_grade'] == 3){
                $storeId[] = $userInfo['store_id'];
            }elseif ($userInfo['jmyc_grade'] == 4){
                $whereU['spread_uid'] = $userInfo['uid'];
                $whereU['jmyc_grade'] = 3;
                $storeId = \app\admin\model\HtnsUser::where($whereU)->column('store_id');
            }
            $storeId = array_filter(array_unique($storeId));
            $this->storeId = $storeId;
        }
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index($export = 0)
    {
        $uid = input('id');
        $type = input('type');
        if ($this->request->isAjax() || $export) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            // 自定义搜索条件解析
            $whereArr = [];
            $filter   = input('filter');
            $filter = htmlspecialchars_decode($filter);// html特殊字符转化&quot;转换为'
            if ($filter) {
                $filterArr = json_decode($filter, true);
                if (isset($filterArr['oid']) && $filterArr['oid']) {
                    $whereArr[] = ['oid', '=', $filterArr['oid']];
                }
                if (isset($filterArr['orderId']) && $filterArr['orderId']) {
                    $whereO['order_id'] = $filterArr['orderId'];
                    $order = HtnsOrder::where($whereO)->find();
                    $whereArr[] = ['oid', '=', $order['id']];
                }
                if (isset($filterArr['grade3Phone'])  && $filterArr['grade3Phone']) {
                    $whereU[] = ['phone|uid|real_name','like','%'.$filterArr['grade3Phone'].'%'];
                    $user = \app\admin\model\HtnsUser::where($whereU)->find();
                    if($user){
                        $whereArr[] = ['grade3_uid', '=', $user['uid']];
                    }
                }
                if (isset($filterArr['grade4Phone']) && $filterArr['grade4Phone']) {
                    $whereU[] = ['phone|uid|real_name','like','%'.$filterArr['grade4Phone'].'%'];
                    $user = \app\admin\model\HtnsUser::where($whereU)->find();
                    if($user){
                        $whereArr[] = ['grade4_uid', '=', $user['uid']];
                    }
                }
                if (isset($filterArr['create_time']) && $filterArr['create_time']) {
                    $createTimeArr = explode(' - ',$filterArr['create_time']);
                    $whereArr[] = ['create_time', 'between', [strtotime($createTimeArr[0]) , strtotime($createTimeArr[1])]];
                }
            }
            if ($export) {
                $page  = 1;
                $limit = 10000;
            }
            $uid = input('uid');
            if($type == 'huoqu'){
                if($uid){
                    $whereArr[] = ['grade3_uid|grade4_uid','=',$uid];
                }
            }else{
                // 查询某个用户列表数据
                if($uid){
                    $whereArr[] = ['source_uid','=',$uid];
                }
            }
            if($this->storeId){
                $whereArr[] = ['o.store_id','in',$this->storeId];
            }
            $count = $this->model
                ->alias('rpo')
                ->where($whereArr)
                ->count();
            $list  = $this->model
                ->where($whereArr)
                ->page($page, $limit)
                ->order($this->sort)
                ->select()->toArray();
            // 门店信息
            $whereS['delete_time'] = 0;
            $store = HtnsBasestationStore::where($whereS)->column('id,name');
            $storeArr = array_column($store,'name','id');
            foreach ($list as &$v) {
                $order = HtnsOrder::find($v['oid']);
                $v['orderId'] = $order['order_id'];
                // 购买用户信息
                $user = \app\admin\model\HtnsUser::find($v['source_uid']);
                $grade = $user->getGradeName($user['jmyc_grade']);
                $v['userInfo'] = $user['uid'].'|'.$user['real_name'].'|'.$user['phone'].'|'.$grade;

                // 社群节点用户信息
                $v['grade3UserInfo'] = '';
                $user3 = \app\admin\model\HtnsUser::find($v['grade3_uid']);
                $jmyc_grade3 = isset($user3['jmyc_grade']) ? $user3['jmyc_grade']:0;
                if($jmyc_grade3){
                    $grade3 = $user3->getGradeName($jmyc_grade3);
                    $v['grade3UserInfo'] = $user3['uid'].'|'.$user3['real_name'].'|'.$user3['phone'].'|'.$grade3;
                }
                // 联盟节点用户信息
                $v['grade4UserInfo'] = '';
                $user4 = \app\admin\model\HtnsUser::find($v['grade4_uid']);
                $jmyc_grade4 = isset($user4['jmyc_grade']) ? $user4['jmyc_grade']:0;
                if($jmyc_grade4){
                    $grade4 = $user4->getGradeName($user4['jmyc_grade']);
                    $v['grade4UserInfo'] = $user4['uid'].'|'.$user4['real_name'].'|'.$user4['phone'].'|'.$grade4;
                }
                $v['storeInfo'] = '';
                if(isset($storeArr[$order['store_id']])){
                    $v['storeInfo'] = $order['store_id'].'|'.$storeArr[$order['store_id']];
                }
            }
            // 导出
            if ($export) {
                return $list;
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        $this->assign('uid',$uid);
        $this->assign('type',$type);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        $activityId = 9;
        $this->assign('activityId', $activityId);
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {

                $activityProductService = new ActivityProductService();

                $rev = $activityProductService->checkProductStock($post['product_id'],$post['stock']);
                if(!$rev['code']){
                    $this->error('保存失败1:'.$rev['msg']);
                }
                $rev = $activityProductService->checkProductIsActivity($post['product_id']);
                if(!$rev['code']){
                    $this->error('保存失败1:'.$rev['msg']);
                }

                // 默认值
                $product = HtnsProduct::find($post['product_id']);

                $post['image'] = $product['image'];
                $post['product_name'] = $product['store_name'];
//                $post['intro'] = $product['store_info'];
                $post['one_buy_limit_num'] = 9999;
                $post['all_buy_limit_num'] = 9999;
                // 折扣专区
                $post['cate_id'] = 0;
                $post['htns_activity_id'] = 9;
                $post['day_stock'] = 9999;
                $post['sum_stock'] = 9999;

                $post['start_time'] = time();
                $post['end_time'] = $post['start_time'] + 7 * 3600 * 24;//默认参与活动7天时间
                $save = $this->model->save($post);
            } catch (Exception $e) {
                $this->error('保存失败2:' . $e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败3');
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $activityId = 8;
        $this->assign('activityId', $activityId);
        $row = $this->model->find($id);
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {

                $activityProductService = new ActivityProductService();

                $rev = $activityProductService->checkProductStock($post['product_id'],$post['stock']);
                if(!$rev['code']){
                    $this->error('保存失败1:'.$rev['msg']);
                }
                $rev = $activityProductService->checkProductIsActivity($post['product_id'] , $id);
                if(!$rev['code']){
                    $this->error('保存失败1:'.$rev['msg']);
                }

                $save = $row->save($post);
            } catch (Exception $e) {
                $this->error('保存失败2:' . $e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败3');
        }
        $this->assign('row', $row);
        return $this->fetch();
    }

    // 有效商品列表
    /**
     * @NodeAnotation(title="有效商品列表")
     */
    public function product_list()
    {
        $ret['code'] = 1;
        $ret['msg']  = '获取成功';
        $ret['data'] = [];

        $where[]     = ['is_show', '=', 1];
        $where[]     = ['is_del', '=', 0];
        $htnsProduct = HtnsProduct::where($where)->order('id desc')->select()->toArray();
        if ($htnsProduct) {
            foreach ($htnsProduct as $v) {
                $retv          = [
                    'id'         => $v['id'],
                    'store_name' => $v['store_name'],
                    'store_info' => $v['id'] . '-' . $v['store_name'],
                ];
                $ret['data'][] = $retv;
            }
        }
        return json($ret);
    }

}